// pages/cart/cart.js
import {asyncWx}  from '../../utils/util'
// const {asyncWx}=require('../../utils/util')
console.log('asyncWx',asyncWx);
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  onShow() {
    const address = wx.getStorageSync('address') || {}
    const cart = wx.getStorageSync('cart') || [];
    this.countCart(cart)
    this.setData({
      address
    })
  },
  //点击收获地址
  handlerChooseAddress() {
    console.log('点击收获地址');
    //获取收获地址
    //获取用户对小程序的权限状态scope  有(允许)true或者（取消）false，false诱导用户打开授权
    // 或者（没点）undefined
    this.getSettingScope().then(() => {
      wx.chooseAddress({
        success: (reslut) => {
          console.log('reslut', reslut);
          this.setData({
            address: reslut
          })
          //存入缓存
          wx.setStorageSync('address', reslut)
        }
      })
    })
  },
  //获取权限判断
  getSettingScope() {
    return new Promise((reslove, reject) => {

      wx.getSetting({
        success: (res) => {
          const { authSetting } = res;
          const scopeAddress = authSetting["scope.address"];
          if (scopeAddress == true || scopeAddress == undefined) {
            reslove();
          } else {
            //用户拒绝过
            wx.openSetting({
              success: (res) => {
                console.log('resres', res)
                const { authSetting } = res;
                const scopeAddress = authSetting["scope.address"];
                if (scopeAddress == true) reslove()
              },
            })
          }
        }
      })

    });
  },
  hanlerItemChange(e) {
    //获取被修改的商品id
    const { id } = e.currentTarget.dataset;
    console.log('id', id);
    let { cart } = this.data;
    let index = cart.findIndex(v => v.goods_id === id);
    //选中状态取反
    cart[index].checked = !cart[index].checked;
    //设置data和缓存
    this.setData({
      cart
    })
    //重新计算全选价格
    this.countCart(cart);
  },
  countCart(cart) {
    //计算全选
    //every遍历，必须保证每一个回调函数都返回true,假如有一个false则中断循环，返回false
    //every是空数组则返回true
    let allChecked = cart.length ? cart.every(v => v.checked) : false;
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.num * v.goods_price;
        totalNum += v.num;
      }
    });
    this.setData({
      allChecked,
      totalPrice,
      totalNum,
      cart
    })
    wx.setStorageSync('cart', cart);
  },
  hanlerItemAllChange(e) {
    console.log('e', e);
    let { cart, allChecked } = this.data;
    //修改值，取反
    allChecked = !allChecked;
    //修改cart
    cart.forEach(v => v.checked = allChecked);
    this.countCart(cart);
  },
  handlerItemNumEdit(e) {
    //编辑加减数量
    //获取事件传过来的参数
    const { id, operation } = e.currentTarget.dataset;
    let { cart } = this.data;
    //找到需要修改的索引
    const index = cart.findIndex(v => v.goods_id === id);
    //判断是否执行删除
    if (cart[index].num === 1 && operation === -1) {
      wx.showModal({
        title: '提示',
        content: '是否要删除该商品？'
      }).then(res => {
        if (res.confirm) {
          cart.splice(index, 1);
          this.countCart(cart);
        }
      })
    } else {
      //进行修改数量
      cart[index].num += operation;
      this.countCart(cart)
    }

  },
  handleBuy(){
    const {address,totalNum}=this.data;
    console.log('点击结算');
    if(!address.userName){
      wx.showToast({
        title: '您还没有选择收获地址',
        icon: 'none',
        mask: true
      })
      return;
    }
    if(totalNum===0){
      wx.showToast({
        title: '您还没有选购商品',
        icon: 'none',
        mask: true
      })
      return;
    }
    //跳转支付页面
    wx.navigateTo({
      url: '/pages/pay/pay',
    })
  }

})